﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.Awesome.Mvc;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class HobbyLookupController : LookupController
    {
        private readonly IRepo<Hobby> repo;

        public HobbyLookupController(IRepo<Hobby> repo)
        {
            this.repo = repo;
        }

        //selected is the selected values when multiselect = true
        [HttpPost]
        public ActionResult Search(string search, IEnumerable<int> selected, int? page = null)
        {
            if (page.HasValue)
            {
                const int pageSize = 6;
                var src =
                    repo.GetAll().Where(o => (selected == null || !selected.Contains(o.Id)) && o.Name.Containz(search));
                var rows = this.RenderView(@"Awesome\LookupList", src.Skip((page.Value - 1) * pageSize).Take(pageSize));
                return Json(new { rows, more = src.Count() > page * pageSize });
            }
            return View(@"Awesome\LookupList", repo.GetAll().Where(o => (selected == null || !selected.Contains(o.Id)) && o.Name.Containz(search)));
        }

        //gets the text do display in the textbox when multiselect = false
        public ActionResult Get(int id)
        {
            return Content((repo.Get(id) ?? new Hobby()).Name);
        }

        #region needed only if you use multiselect = true
        public ActionResult Selected(IEnumerable<int> selected)
        {
            return View(@"Awesome\LookupList", repo.GetAll().Where(o => selected != null && selected.Contains(o.Id)));
        }

        public ActionResult GetMultiple(IEnumerable<int> selected)
        {
            return Json(repo.GetAll().Where(o => selected.Contains(o.Id)).Select(v => new { Text = v.Name }));
        }
        #endregion
    }
}